package cn.myra.program;

import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class ObjectIO {
	
	
	public static void writeFile(File file,List<User> list) {
		
		try {
			if(!file.exists()) {
				file.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(file);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			
			oos.writeObject(list);
			oos.flush();
			
			if(oos!=null) {
				oos.close();
			}
			if(fos!=null) {
				fos.close();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			
		}
		
	}
	
	@SuppressWarnings("unchecked")
	public static List readFile(File file) {
		List<User> list= new ArrayList<>();
		FileInputStream fis;
		ObjectInputStream  ois;
		
		try {
			if(!file.exists()) {
				file.createNewFile();
			}
			
			fis = new FileInputStream(file);
			ois = new ObjectInputStream(fis);
			list=(List<User>)ois.readObject();
			for (User user : list) {
				System.out.println(user);
			}

			if(ois!=null) {
				ois.close();
			}
			if(fis!=null) {
				fis.close();
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
}
